package com.ocom.payhandle.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.card.EntityXfAccountType;
import com.ocom.common.entity.card.EntityXfDeviceInfo;
import com.ocom.common.entity.card.EntityXfMealTime;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.payconfig.EntityXfDeviceMealConfig;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.pyhandle.GetMachParaVo;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.ChangeMachParaStateVo;
import com.ocom.payhandle.vo.HeartDataVo;
import com.ocom.payhandle.vo.MachineDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
public class MachParaController {


    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private CompanyConfigService companyConfigService;

    @Autowired
    private XfMealTimeService xfMealTimeService;

    @Autowired
    private XfDeviceMealConfigServcie xfDeviceMealConfigServcie;

    @Autowired
    private XfAccountTypeService xfAccountTypeService;

    /**
     * 获取设备参数（getMachPara）
     * */
    @PostMapping(PayHandleUrl.URL_PayHandle_GetMachPara)
    public Result GetMachPara(@Validated @RequestBody GetMachParaVo getMachParaVo){
        if (getMachParaVo.getCompanyId() == null || getMachParaVo.getMachNo() == null){
            return ResultUtil.error(ResultEnum.Err_203);
        }

        //jobID = xf_device_info. para_state
        EntityXfDeviceInfo entityDeviceInfo = deviceInfoService.GetDeviceInfo(getMachParaVo.getCompanyId(), getMachParaVo.getMachNo());
        if (entityDeviceInfo == null){
            return ResultUtil.error(ResultEnum.Err_2013);
        }
        Long jobId = 0l;
        if(!CommonUtil.isNull(entityDeviceInfo.getParaJobid())){
            jobId = Long.valueOf(entityDeviceInfo.getParaJobid());
        }

        //心跳间隔时间（支付时间）参数 heart_data：
        //			{ “heartBeatNum” : 60 , “cancelFlag”: 1 , “payTimes”: 10 , “payInterval” : 3 }
        HeartDataVo heartDataVo = new HeartDataVo();
        heartDataVo.setHeartBeatNum(30);
        heartDataVo.setCancelFlag(0);
        heartDataVo.setPayTimes(10);
        heartDataVo.setPayInterval(3);
        heartDataVo.setFaceInterval(60);
        //设备参数machine_data：
        //		A. 从分库餐段时间表xf_meal_time查找就餐时段
        //				select meal_no , begin_time , end_time from xf_meal_time
        //				where com_id = companyID and point_id = 0 and acc_type_no = 0
        //				order by meal_no
        //			例如查询结果是： { “meal_no” : 2 , “begin_time” : “11:30:00” , “end_time” : “13:30:00” } ,
        //							{ “meal_no” : 3 , “begin_time” : “17:30:00” , “end_time” : “19:00:00” }
        //											注意：没有餐段1
        //					应该返回 mealResTime=“00:00-00:00, 11:30-13:30, 17:30-19:00”
        List<EntityXfMealTime> entityXfMealTimes = xfMealTimeService.getMealInfo(getMachParaVo.getCompanyId());
//        if (entityXfMealTimes.size() == 0){
//            return ResultUtil.error(ResultEnum.Err_1000,"餐段信息");
//        }
        MachineDataVo machineDataVo = new MachineDataVo();
    //    machineDataVo.setConsType(1);
        machineDataVo.setConsType(entityDeviceInfo.getConsType());

        machineDataVo.setDeviceMode(entityDeviceInfo.getDeviceMode());

        machineDataVo.setDeviceName(entityDeviceInfo.getDeviceName());

        machineDataVo.setFaceAuth(entityDeviceInfo.getFaceAuth());
        machineDataVo.setFaceAuthTime(entityDeviceInfo.getFaceAuthTime());
        machineDataVo.setFaceAuthType(entityDeviceInfo.getFaceAuthType());

        /*List<String> mealResTime = machineDataVo.getMealResTime();
        for (EntityXfMealTime entityXfMealTime: entityXfMealTimes) {
            Integer mealNo = Integer.valueOf(entityXfMealTime.getMealNo());
            String mealTime = entityXfMealTime.getBeginTime().substring(0,5) + "-" + entityXfMealTime.getEndTime().substring(0,5);
            if (entityXfMealTimes.size() == 1 && mealNo == 1){
                mealResTime.add(mealTime);
            }else if (entityXfMealTimes.size() == 1 && mealNo == 2 || entityXfMealTimes.size() == 2 && mealNo == 2||
                    entityXfMealTimes.size() == 3 && mealNo == 2 || entityXfMealTimes.size() == 4 && mealNo == 2){
                mealTime = "00:00-00:00," + mealTime;
                mealResTime.add(mealTime);
            }else if (entityXfMealTimes.size() == 1 && mealNo == 3 || entityXfMealTimes.size() == 2 && mealNo == 3||
                    entityXfMealTimes.size() == 3 && mealNo == 3){
                mealTime = "00:00-00:00,00:00-00:00," + mealTime;
                mealResTime.add(mealTime);
            }else if (entityXfMealTimes.size() == 1 && mealNo == 4 || entityXfMealTimes.size() == 2 && mealNo == 4){
                mealTime = "00:00-00:00,00:00-00:00,00:00-00:00," + mealTime;
                mealResTime.add(mealTime);
            }else if (entityXfMealTimes.size() == 1 && mealNo == 5){
                mealTime = "00:00-00:00,00:00-00:00,00:00-00:00,00:00-00:00," + mealTime;
                mealResTime.add(mealTime);
            }
        }
        machineDataVo.setMealResTime(mealResTime);*/
        Map<String, Object> map = new HashMap<>();
        map.put("jobId",jobId);
        map.put("heartData", heartDataVo);
        map.put("machineData",machineDataVo);
        map.put("meal",entityXfMealTimes);
        return ResultUtil.success(map);
    }


    @PostMapping(PayHandleUrl.URL_PayHandle_GetMachParaTwo)
    public Result getMachParaTwo(@Validated @RequestBody GetMachParaVo getMachParaVo){
        if (getMachParaVo.getCompanyId() == null || getMachParaVo.getMachNo() == null){
            return ResultUtil.error(ResultEnum.Err_203);
        }

        //jobID = xf_device_info. para_state
        EntityXfDeviceInfo entityDeviceInfo = deviceInfoService.GetDeviceInfo(getMachParaVo.getCompanyId(), getMachParaVo.getMachNo());
        if (entityDeviceInfo == null){
            return ResultUtil.error(ResultEnum.Err_2013);
        }
        Long jobId = 0l;
        if(!CommonUtil.isNull(entityDeviceInfo.getParaJobid())){
            jobId = Long.valueOf(entityDeviceInfo.getParaJobid());
        }

        //心跳间隔时间（支付时间）参数 heart_data：
        //			{ “heartBeatNum” : 60 , “cancelFlag”: 1 , “payTimes”: 10 , “payInterval” : 3 }
        HeartDataVo heartDataVo = new HeartDataVo();
        heartDataVo.setHeartBeatNum(30);
        heartDataVo.setCancelFlag(0);
        heartDataVo.setPayTimes(10);
        heartDataVo.setPayInterval(3);
        heartDataVo.setFaceInterval(60);

        MachineDataVo machineDataVo = new MachineDataVo();
        machineDataVo.setConsType(entityDeviceInfo.getConsType());
        machineDataVo.setDeviceMode(entityDeviceInfo.getDeviceMode());
        machineDataVo.setDeviceName(entityDeviceInfo.getDeviceName());

        machineDataVo.setFaceAuth(entityDeviceInfo.getFaceAuth());
        machineDataVo.setFaceAuthTime(entityDeviceInfo.getFaceAuthTime());
        machineDataVo.setFaceAuthType(entityDeviceInfo.getFaceAuthType());

        List<EntityXfMealTime> entityXfMealTimes = xfMealTimeService.selectTimeList3(getMachParaVo.getCompanyId(),entityDeviceInfo.getPointId().longValue(),0);

        List<EntityXfDeviceMealConfig> xfDeviceMealConfigList=xfDeviceMealConfigServcie.selectMealNo(getMachParaVo.getCompanyId(),entityDeviceInfo.getConsType(),getMachParaVo.getMachNo());

        List<Map<String, Object>> mealParaList=new ArrayList<>();

        List<EntityXfAccountType> accountTypes=xfAccountTypeService.selectAccountTypes(getMachParaVo.getCompanyId());

        List<EntityXfMealTime> xfMealTimesNew = new ArrayList<>();
//        if(entityDeviceInfo.getPointId()!=null && entityDeviceInfo.getPointId()>0){
//            xfMealTimesNew = xfMealTimeService.selectTimeList2(getMachParaVo.getCompanyId(),entityDeviceInfo.getPointId().longValue());
//        }

        List<EntityXfMealTime> entityXfMealInfo = xfMealTimeService.getMealInfo(getMachParaVo.getCompanyId());
        Map<String, String> comStatusCountMap = new HashMap<>();
        if(entityXfMealInfo!=null && entityXfMealInfo.size()>0){
            //list转map
            comStatusCountMap = entityXfMealInfo.stream().collect(Collectors.toMap(e -> e.getMealNo(),
                    e -> e.getMealName(),
                    (e1, e2) -> e1));
        }

        if (entityDeviceInfo.getConsType()>1){
            Map<String, Object> mealPara = new HashMap<>();

            mealPara.put("cosumerMode",1);
            mealPara.put("mealMoney","10000");
            mealPara.put("voucherMode","0");
            mealPara.put("AccountTypes","");
            mealPara.put("typesName","");
            mealPara.put("mealNo","0");
            mealPara.put("mealName","全天");
            mealPara.put("beginTime","00:00");
            mealPara.put("endTime","23:59");

            mealPara.put("accTypeTimes", new ArrayList<>());
            if (xfMealTimesNew != null && xfMealTimesNew.size() > 0) {
                List<EntityXfMealTime> timeList = new ArrayList<>();
                for (EntityXfMealTime entityXfMealTime1 : xfMealTimesNew) {
                    if (entityXfMealTime1.getMealNo().equals((String) mealPara.get("mealNo"))) {
                        timeList.add(entityXfMealTime1);
                    }
                }
                mealPara.put("accTypeTimes", timeList);
            }

            for (EntityXfDeviceMealConfig entityXfDeviceMealConfig : xfDeviceMealConfigList) {
                if(entityDeviceInfo.getConsType().compareTo(entityXfDeviceMealConfig.getConsType())!=0 ) continue;
                String mealNo= String.valueOf(entityXfDeviceMealConfig.getMealNo());
                if (mealNo.equals("0")){
                    mealPara.put("cosumerMode",entityXfDeviceMealConfig.getKeyMode());
                    mealPara.put("mealMoney",entityXfDeviceMealConfig.getMealMoney());
                    mealPara.put("voucherMode",entityXfDeviceMealConfig.getVoucherMode());
                    if (StringUtils.isNotEmpty(entityXfDeviceMealConfig.getAccountIds())){
                        String typesName="";
                        String[] arr=entityXfDeviceMealConfig.getAccountIds().split(",");
                        for (EntityXfAccountType accountType : accountTypes) {
                            for (int i = 0; i < arr.length; i++) {
                                if(CommonUtil.isNull(arr[i])){
                                    continue;
                                }
                                Integer accTypeId= Integer.valueOf(arr[i]);
                                if (accountType.getAccTypeId().compareTo(accTypeId)==0){
                                    if (i==0){
                                        typesName=accountType.getAccTypeName();
                                    }else {
                                        typesName=typesName+","+accountType.getAccTypeName();
                                    }
                                }
                            }
                        }
                        mealPara.put("AccountTypes",entityXfDeviceMealConfig.getAccountIds());
                        mealPara.put("typesName",typesName);
                    }
                }
            }

            mealParaList.add(mealPara);
        }else{
            for (EntityXfMealTime entityXfMealTime : entityXfMealTimes) {
                Map<String, Object> mealPara = new HashMap<>();

                mealPara.put("cosumerMode",1);
                mealPara.put("mealMoney","10000");
                mealPara.put("voucherMode","0");
                mealPara.put("AccountTypes","");
                mealPara.put("typesName","");

                mealPara.put("mealNo",entityXfMealTime.getMealNo());
                mealPara.put("mealName","");
                if(comStatusCountMap.containsKey(entityXfMealTime.getMealNo())){
                    mealPara.put("mealName",comStatusCountMap.get(entityXfMealTime.getMealNo()));
                }
                mealPara.put("beginTime",entityXfMealTime.getBeginTime());
                mealPara.put("endTime",entityXfMealTime.getEndTime());

                mealPara.put("accTypeTimes", new ArrayList<>());
                if (xfMealTimesNew != null && xfMealTimesNew.size() > 0) {
                    List<EntityXfMealTime> timeList = new ArrayList<>();
                    for (EntityXfMealTime entityXfMealTime1 : xfMealTimesNew) {
                        if (entityXfMealTime1.getMealNo().equals((String) mealPara.get("mealNo"))) {
                            timeList.add(entityXfMealTime1);
                        }
                    }
                    mealPara.put("accTypeTimes", timeList);
                }

                for (EntityXfDeviceMealConfig entityXfDeviceMealConfig : xfDeviceMealConfigList) {
                    String mealNo= String.valueOf(entityXfDeviceMealConfig.getMealNo());
                    if (entityXfMealTime.getMealNo().equals(mealNo) && entityDeviceInfo.getConsType().compareTo(entityXfDeviceMealConfig.getConsType())==0){
                        mealPara.put("cosumerMode",entityXfDeviceMealConfig.getKeyMode());
                        mealPara.put("mealMoney",entityXfDeviceMealConfig.getMealMoney());
                        mealPara.put("voucherMode",entityXfDeviceMealConfig.getVoucherMode());
                        if (StringUtils.isNotEmpty(entityXfDeviceMealConfig.getAccountIds())){
                            String typesName="";
                            String[] arr=entityXfDeviceMealConfig.getAccountIds().split(",");
                            for (EntityXfAccountType accountType : accountTypes) {
                                for (int i = 0; i < arr.length; i++) {
                                    if(CommonUtil.isNull(arr[i])){
                                        continue;
                                    }
                                    Integer accTypeId= Integer.valueOf(arr[i]);
                                    if (accountType.getAccTypeId().compareTo(accTypeId)==0){
                                        if (i==0){
                                            typesName=accountType.getAccTypeName();
                                        }else {
                                            typesName=typesName+","+accountType.getAccTypeName();
                                        }
                                    }
                                }
                            }
                            mealPara.put("AccountTypes",entityXfDeviceMealConfig.getAccountIds());
                            mealPara.put("typesName",typesName);
                        }
                    }
                }
                mealParaList.add(mealPara);
            }
        }


        machineDataVo.setMealPara(mealParaList);

        EntityCompanyConfig entityCompanyConfig = companyConfigService.getTapValue(getMachParaVo.getCompanyId(), "cardRead");
        if (entityCompanyConfig != null) {
            machineDataVo.setCardRead(Integer.valueOf(entityCompanyConfig.getConfig()));
        }

        try{
            EntityCompanyConfig entityCompanyConfig1 = companyConfigService.getTapValue(getMachParaVo.getCompanyId(), "jhParam");
            if (entityCompanyConfig1 != null) {
                Map<String, Object> objectMap = JSON.parseObject(entityCompanyConfig1.getConfig(),HashMap.class);
                machineDataVo.getParam().putAll(objectMap);
            }
        }catch (Exception e){
            log.error("建行参数获取异常 【{}】",e);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("jobId",jobId);
        map.put("heartData", heartDataVo);
        map.put("machineData",machineDataVo);
        map.put("mealPara",mealParaList);
        //map.put("meal",entityXfMealTimes);
        return ResultUtil.success(map);
    }

    /**
     * 2.5.2 更改设备参数状态（changeMachParaState）
     * */
    @PostMapping(PayHandleUrl.URL_PayHandle_ChangeMachParaState)
    public Result ChangeMachParaState(@Validated @RequestBody ChangeMachParaStateVo changeMachParaStateVo){
        //1、修改消费设备表xf_device_info中com_id、device_no匹配的记录：
        //update  xf_device_info set para_state = 0
        //where  com_id = companyID and device_no = “machNo” and para _jobid = jobId
        if (changeMachParaStateVo.getCompanyId() == null || changeMachParaStateVo.getCompanyId() < 1 ||
          changeMachParaStateVo.getMachNo().isEmpty() || changeMachParaStateVo.getJobId().isEmpty()){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("updataFlag",0);
        try {
            Boolean b = deviceInfoService.updateJobId(changeMachParaStateVo.getCompanyId(),changeMachParaStateVo.getMachNo(),
                    changeMachParaStateVo.getJobId());
            if(!b){
                map.put("updataFlag",1);
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        //返回 updataFlag =0
        return ResultUtil.success(map);
    }

}
